package com.demo.多线程;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Program: Java
 * @ClassName ConditionLock
 * @Description: Condition精准通知唤醒
 * @Author: liutao
 * @Create: 2024/5/30 14:42
 * @Version 1.0
 **/
public class ConditionLock {

    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            data.increase();
        }, "A").start();

        new Thread(()->{
            data.decrease();
        }, "B").start();
    }
}

class Data {
    private final Lock lock = new ReentrantLock();
    private final Condition increase = lock.newCondition();
    private final Condition decrease = lock.newCondition();
    private int num = 0;

    public void increase() {
        lock.lock();
        try {
            while (num != 0) {
                // 等待
                increase.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName() + ":res:"+ num);
            // 唤醒所有
            increase.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }

    }

    public void decrease() {
        lock.lock();
        try {
            while (num != 1) {
                // 等待
                decrease.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName() + ":res:"+ num);
            // 唤醒所有
            decrease.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }
}
